const jwt = require("jsonwebtoken");
const User = require("../models/users");
const config = require('../config/default')

class UserController {
  async fild(ctx) {
    let { pageIndex = 1, pageSize = 10 } = ctx.query
    pageIndex = Number(pageIndex)
    pageSize = Number(pageSize)
    const user = await User.find({},{password: 0}).limit(pageSize).skip((pageIndex-1)*pageSize) // limit: 查询多少条；skip：跳过多少条
    const total = await User.count()
    const data = {
      data: user,
      total,
      pageIndex,
      pageSize
    }
    ctx.success(data)
  }
  async login(ctx) {
    const {username, password} = ctx.request.body
    if(!username || !password) return ctx.fail('参数错误')
    const isUser = await User.findOne({username});
    if (!isUser) return ctx.fail('该账号未注册')
    const user = await User.findOne(ctx.request.body);
    if (!user) return ctx.fail('密码错误')
    const token = jwt.sign({_id: user._id, username: user.username}, config.secret, {expiresIn: '1d'});  // 登录成功返回jwt加密后的token信息有效期一天
    ctx.success(token)
  }
  async create(ctx) {
    const {username, password} = ctx.request.body
    if(!username || !password) return ctx.fail('参数错误')
    const isUser = await User.findOne({username});
    if (isUser) return ctx.fail('该账号已注册')
    const user = await new User(ctx.request.body).save();
    const token = jwt.sign({_id: user._id, username: user.username}, config.secret, {expiresIn: '1d'});  // 登录成功返回jwt加密后的token信息有效期一天
    ctx.success(token)
  }
}

module.exports = new UserController()